<!--
 * @Author: wjc
 * @Date: 2025-02-13 14:52:31
 * @LastEditors: wjc
 * @LastEditTime: 2025-10-28 14:32:52
 * @Description: 
-->
<template>
  <div class="pagination">
    <el-pagination
      v-show="total !== 0"
      :background="background"
      :layout="layout"
      :total="total"
      :current-page="getPage"
      :page-size="getLimit"
      :page-sizes="pageSizes"
      :popper-class="limit.toString()"
      v-bind="$attrs"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script setup lang="ts">
  import { scrollTo } from '#/utils/scroll-to'

  defineOptions({
    name: 'Pagination',
  })

  const props = withDefaults(
    defineProps<{
      autoScroll?: boolean
      background?: boolean
      layout?: string
      limit?: number
      page?: number
      pageSizes?: number[]
      total: number
    }>(),
    {
      page: 1,
      limit: 10,
      pageSizes: () => [10, 15, 30, 50],
      layout: 'prev, pager, next, jumper, ->, total, sizes',
      background: true,
      autoScroll: true,
    }
  )

  const emits = defineEmits<{
    (e: 'update:page', page: number): void
    (e: 'update:limit', limit: number): void
    (e: 'on-changed'): void
  }>()

  const getPage = computed({
    get(): number {
      return props.page
    },
    set(val) {
      emits('update:page', val)
    },
  })

  const getLimit = computed({
    get(): number {
      return props.limit
    },
    set(val) {
      emits('update:limit', val)
    },
  })

  const handleSizeChange = (val: number) => {
    emits('update:page', 1) // getPage.value
    emits('update:limit', val)
    emits('on-changed')

    if (props.autoScroll) scrollTo(0, 800, null)
  }

  const handleCurrentChange = (val: number) => {
    emits('update:page', val)
    emits('update:limit', getLimit.value)
    // emits('on-change', { page: val, page_limit: getLimit.value })
    emits('on-changed')

    if (props.autoScroll) scrollTo(0, 800, null)
  }
</script>

<style lang="scss" scoped>
  .pagination {
    @apply pt-15px pb-15px pl-15px pr-5px;

    :deep(.el-pagination__sizes) {
      @apply mr-10px;
    }
  }
</style>
